package utils;


import java.io.*;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.zip.*;

/**
 * User Canno Date 2018/1/4 Time 11:36
 */
@SuppressWarnings("Duplicates")
public class ZipUtils {

    public static final String UNCOMPRESS_TMP = "-UncompressTmp-";
    private static final int  BUFFER_SIZE = 2 * 1024;

    private static final String CODING_UTF8 = "UTF-8";
    private static final String CODING_GBK = "GBK";




    /**
     * 压缩文件
     *
     * @param sourceFilePath 源文件路径
     * @param zipFilePath    压缩后文件存储路径
     * @param zipFilename    压缩文件名
     * @param isDirCompress   是否单文件夹压缩
     */
    public static void compressToZip(String sourceFilePath, String zipFilePath, String zipFilename,boolean isDirCompress) {
        File sourceFile = new File(sourceFilePath);
        File zipPath = new File(zipFilePath);
        if (!zipPath.exists()) {
            zipPath.mkdirs();
        }
        File zipFile = new File( zipPath+File.separator+zipFilename);
        try (FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
             ZipOutputStream zos = new ZipOutputStream(fileOutputStream)) {
             writeZip(sourceFile, "", zos,isDirCompress);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 遍历所有文件，压缩
     *
     * @param file       源文件目录
     * @param parentPath 压缩文件目录
     * @param zos        文件流
     */
    public static void writeZip(File file, String parentPath, ZipOutputStream zos,boolean isDirCompress) throws Exception{
        if (file.isDirectory()) {
            //目录
            if(!file.getName().contains(UNCOMPRESS_TMP)){
                parentPath =parentPath+ file.getName() + File.separator;
            }
            File[] files = file.listFiles();
            if(files.length==0){
                zos.putNextEntry(new ZipEntry(parentPath + "/"));
            }else {
                for (File f : files) {
                    writeZip(f, parentPath, zos,isDirCompress);
                }
            }
        } else {
            //文件
            try (FileInputStream fileInputStream = new FileInputStream(file);
                 BufferedInputStream bis = new BufferedInputStream(fileInputStream)) {
                ZipEntry zipEntry = null;
                if(isDirCompress){
                    //指定zip文件夹
                    zipEntry = new ZipEntry(parentPath + file.getName());
                }else {
                    //生成的zip不包含该文件夹
                    zipEntry = new ZipEntry(file.getName());
                }
                zos.putNextEntry(zipEntry);
                int len;
                byte[] buffer = new byte[1024 * 10];
                while ((len = bis.read(buffer, 0, buffer.length)) != -1) {
                    zos.write(buffer, 0, len);
                    zos.flush();
                }
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }


    /**
     * zip解压
     * @param inputFile 待解压文件名
     * @param destDirPath  解压路径
     */

    public static void zipUncompress(String inputFile,String destDirPath) throws Exception {
        File srcFile = new File(inputFile);//获取当前压缩文件
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        //开始解压
        //构建解压输入流
        try( ZipInputStream zIn = new ZipInputStream(new FileInputStream(srcFile),Charset.forName(CODING_GBK));) {
            ZipEntry entry = null;
            File file = null;
            while ((entry = zIn.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    OutputStream out = null;
                    BufferedOutputStream bos = null;
                    try {
                        file = new File(destDirPath, entry.getName());
                        if (!file.exists()) {
                            new File(file.getParent()).mkdirs();//创建此文件的上级目录
                        }
                        out = new FileOutputStream(file);
                        bos = new BufferedOutputStream(out);
                        int len = -1;
                        byte[] buf = new byte[BUFFER_SIZE];
                        while ((len = zIn.read(buf)) != -1) {
                            bos.write(buf, 0, len);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }finally {
                        // 关流顺序，先打开的后关闭
                        bos.close();
                        out.close();
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        }
    }
}
